package com.hao.myfloatwindow

import android.app.ActivityManager
import android.app.usage.UsageStats
import android.app.usage.UsageStatsManager
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.LauncherApps
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.hao.myfloatserver.FloatClient
import com.hao.myfloatserver.FloatHelper
import com.hao.myfloatserver.IFloatPermissionCallback
import java.text.SimpleDateFormat
import java.util.*

class MainActivity : AppCompatActivity() {

    private var floatHelper: FloatHelper? = null
    private lateinit var ivIcon: ImageView
    private lateinit var tvContent: TextView
    
    // 程序应用显示文本
    private lateinit var tvSelectedApp1: TextView
    private lateinit var tvSelectedApp2: TextView
    private lateinit var tvSelectedApp3: TextView
    private lateinit var tvSelectedApp4: TextView
    private lateinit var tvSelectedApp5: TextView
    
    // 程序应用图标显示
    private lateinit var ivSelectedAppIcon1: ImageView
    private lateinit var ivSelectedAppIcon2: ImageView
    private lateinit var ivSelectedAppIcon3: ImageView
    private lateinit var ivSelectedAppIcon4: ImageView
    private lateinit var ivSelectedAppIcon5: ImageView
    
    // 系统应用开关
    private lateinit var switchShowSystemApps: android.widget.Switch
    
    // 存储选中应用的图标
    private var selectedAppIcon1: Drawable? = null
    private var selectedAppIcon2: Drawable? = null
    private var selectedAppIcon3: Drawable? = null
    private var selectedAppIcon4: Drawable? = null
    private var selectedAppIcon5: Drawable? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)

        val btnShow = findViewById<Button>(R.id.btnShow)
        val btnClose = findViewById<Button>(R.id.btnClose)
        
        // 初始化程序应用显示文本
        tvSelectedApp1 = findViewById(R.id.tvSelectedApp1)
        tvSelectedApp2 = findViewById(R.id.tvSelectedApp2)
        tvSelectedApp3 = findViewById(R.id.tvSelectedApp3)
        tvSelectedApp4 = findViewById(R.id.tvSelectedApp4)
        tvSelectedApp5 = findViewById(R.id.tvSelectedApp5)
        
        // 初始化程序应用图标显示
        ivSelectedAppIcon1 = findViewById(R.id.ivSelectedAppIcon1)
        ivSelectedAppIcon2 = findViewById(R.id.ivSelectedAppIcon2)
        ivSelectedAppIcon3 = findViewById(R.id.ivSelectedAppIcon3)
        ivSelectedAppIcon4 = findViewById(R.id.ivSelectedAppIcon4)
        ivSelectedAppIcon5 = findViewById(R.id.ivSelectedAppIcon5)
        
        // 初始化系统应用开关
        switchShowSystemApps = findViewById(R.id.switchShowSystemApps)
        switchShowSystemApps.setOnCheckedChangeListener { _, isChecked ->
            // 开关状态改变时可以做一些处理，比如保存设置等
            println("Show system apps switch changed to: $isChecked")
        }

        var view = View.inflate(this, R.layout.float_view, null)

        ivIcon = view.findViewById(R.id.ivIcon)
        tvContent = view.findViewById(R.id.tvContent)

        //定义悬浮窗助手
        floatHelper = FloatClient.Builder()
            .with(this)
            .addView(view)
            //是否需要展示默认权限提示弹窗，建议使用自己的项目中弹窗样式（默认开启）
            .enableDefaultPermissionDialog(true)
            .setClickTarget(MainActivity::class.java)
            .addPermissionCallback(object : IFloatPermissionCallback {
                override fun onPermissionResult(granted: Boolean) {
                    //（建议使用addPermissionCallback回调中添加自己的弹窗）
                    //这一句是一个弹出消息  告知用户是否允许显示悬浮窗
                    //Toast.makeText(this@MainActivity, "granted -> $granted", Toast.LENGTH_SHORT).show()
                    if (!granted) {
                        //申请权限
                        floatHelper?.requestPermission()
                    }
                }
            })
            .build()

        btnShow.setOnClickListener {
            //开启悬浮窗
            floatHelper?.show()
        }


        btnClose.setOnClickListener {
            //隐藏悬浮窗
            floatHelper?.dismiss()
        }
        
        // 设置程序按钮点击事件
        findViewById<Button>(R.id.btnAirport1).setOnClickListener {
            showRunningAppsList(1)
        }
        
        findViewById<Button>(R.id.btnAirport2).setOnClickListener {
            showRunningAppsList(2)
        }
        
        findViewById<Button>(R.id.btnAirport3).setOnClickListener {
            showRunningAppsList(3)
        }
        
        findViewById<Button>(R.id.btnAirport4).setOnClickListener {
            showRunningAppsList(4)
        }
        
        findViewById<Button>(R.id.btnAirport5).setOnClickListener {
            showRunningAppsList(5)
        }
        
        // 添加调试按钮
        val debugButton = Button(this)
        debugButton.text = "Debug Apps"
        debugButton.setOnClickListener {
            debugListAllInstalledApps()
        }
        
        // 将调试按钮添加到布局中
        val layout = findViewById<ViewGroup>(android.R.id.content)
        val layoutParams = ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        layout.addView(debugButton, layoutParams)
    }
    
    /**
     * 更新选中应用的显示
     */
    private fun updateSelectedApp(programNumber: Int, appInfo: AppInfo) {
        when (programNumber) {
            1 -> {
                tvSelectedApp1.text = appInfo.name
                selectedAppIcon1 = appInfo.icon
                ivSelectedAppIcon1.setImageDrawable(appInfo.icon)
                ivSelectedAppIcon1.visibility = View.VISIBLE
            }
            2 -> {
                tvSelectedApp2.text = appInfo.name
                selectedAppIcon2 = appInfo.icon
                ivSelectedAppIcon2.setImageDrawable(appInfo.icon)
                ivSelectedAppIcon2.visibility = View.VISIBLE
            }
            3 -> {
                tvSelectedApp3.text = appInfo.name
                selectedAppIcon3 = appInfo.icon
                ivSelectedAppIcon3.setImageDrawable(appInfo.icon)
                ivSelectedAppIcon3.visibility = View.VISIBLE
            }
            4 -> {
                tvSelectedApp4.text = appInfo.name
                selectedAppIcon4 = appInfo.icon
                ivSelectedAppIcon4.setImageDrawable(appInfo.icon)
                ivSelectedAppIcon4.visibility = View.VISIBLE
            }
            5 -> {
                tvSelectedApp5.text = appInfo.name
                selectedAppIcon5 = appInfo.icon
                ivSelectedAppIcon5.setImageDrawable(appInfo.icon)
                ivSelectedAppIcon5.visibility = View.VISIBLE
            }
        }
    }
    
    private fun showRunningAppsList(programNumber: Int) {
        // 检查是否有查看使用情况的权限
        val hasUsagePermission = hasUsageStatsPermission()
        
        // 获取最近使用的用户应用列表（如果有权限）
        val recentlyUsedApps = if (hasUsagePermission) getRecentlyUsedUserApps() else emptyList()
        
        // 获取所有已安装的用户应用列表作为备选
        val allUserAppInfoList = getInstalledAppsFromContentResolver()
        
        // 合并列表：最近使用的应用排在前面
        val appInfoList = if (recentlyUsedApps.isNotEmpty()) {
            (recentlyUsedApps + allUserAppInfoList.filter { appInfo -> 
                recentlyUsedApps.none { it.packageName == appInfo.packageName }
            }).distinctBy { it.packageName }
        } else {
            allUserAppInfoList
        }
        
        // 添加调试信息
        println("Recently used apps count: ${recentlyUsedApps.size}")
        println("All user apps count: ${allUserAppInfoList.size}")
        println("Final apps count: ${appInfoList.size}")
        
        // 查找微信应用
        val weChatApp = appInfoList.find { 
            it.packageName == "com.tencent.mm" || 
            it.name.contains("微信") ||
            it.name.contains("WeChat") 
        }
        
        if (weChatApp != null) {
            println("WeChat found: ${weChatApp.name}, package: ${weChatApp.packageName}")
        } else {
            println("WeChat not found in apps list")
            // 打印前10个应用的信息
            println("First 10 apps in list:")
            appInfoList.take(10).forEach { app ->
                println("  ${app.name} (${app.packageName})")
            }
        }
        
        if (appInfoList.isEmpty()) {
            Toast.makeText(this, "未找到应用", Toast.LENGTH_LONG).show()
            return
        }
        
        // 准备显示数据
        val appNames = appInfoList.map { it.name }.toTypedArray()
        val appIcons = appInfoList.map { it.icon as Drawable? }.toTypedArray()
        
        // 创建自定义列表项的对话框
        val dialogBuilder = AlertDialog.Builder(this)
        dialogBuilder.setTitle("选择应用分配给${programNumber}号程序")
        
        // 创建自定义列表视图
        val listView = android.widget.ListView(this)
        val adapter = AppListAdapter(appNames, appIcons)
        listView.adapter = adapter
        
        dialogBuilder.setView(listView)
        val dialog = dialogBuilder.create()
        
        listView.onItemClickListener = android.widget.AdapterView.OnItemClickListener { _, _, position, _ ->
            updateSelectedApp(programNumber, appInfoList[position])
            dialog.dismiss()
        }
        
        dialog.show()
    }
    
    /**
     * 自定义适配器用于显示带图标的列表项
     */
    inner class AppListAdapter(
        private val appNames: Array<String>,
        private val appIcons: Array<Drawable?>
    ) : android.widget.BaseAdapter() {
        
        override fun getCount(): Int = appNames.size
        
        override fun getItem(position: Int): Any = appNames[position]
        
        override fun getItemId(position: Int): Long = position.toLong()
        
        override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
            val view: View = convertView ?: layoutInflater.inflate(android.R.layout.select_dialog_singlechoice, parent, false)
            
            val textView = view as TextView
            textView.text = appNames[position]
            
            // 设置统一大小的图标
            if (appIcons[position] != null) {
                val icon = appIcons[position]?.constantState?.newDrawable()?.mutate()
                icon?.setBounds(0, 0, 120, 120) // 设置统一大小
                textView.setCompoundDrawables(icon, null, null, null)
                textView.compoundDrawablePadding = 40
            }
            
            // 设置文本居中和合适的间距
            textView.textAlignment = View.TEXT_ALIGNMENT_CENTER
            val padding = 16
            textView.setPadding(padding, padding, padding, padding)
            
            return view
        }
    }
    
    /**
     * 应用信息数据类
     */
    data class AppInfo(
        val name: String,
        val packageName: String,
        val icon: Drawable
    )
    
    /**
     * 检查是否具有使用统计权限
     */
    private fun hasUsageStatsPermission(): Boolean {
        // 添加API级别检查
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            return false
        }
        
        val usageStatsManager = getSystemService(USAGE_STATS_SERVICE) as UsageStatsManager
        val currentTime = System.currentTimeMillis()
        val usageStatsList = usageStatsManager.queryUsageStats(
            UsageStatsManager.INTERVAL_DAILY,
            currentTime - 1000 * 60 * 60 * 24, // 24小时内的数据
            currentTime
        )
        return !usageStatsList.isNullOrEmpty()
    }
    
    /**
     * 获取最近使用的用户应用列表（包含图标）
     */
    private fun getRecentlyUsedUserApps(): List<AppInfo> {
        // 添加API级别检查
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            return emptyList()
        }
        
        val usageStatsManager = getSystemService(USAGE_STATS_SERVICE) as UsageStatsManager
        val currentTime = System.currentTimeMillis()
        
        // 获取最近使用统计
        val usageStatsList = usageStatsManager.queryUsageStats(
            UsageStatsManager.INTERVAL_BEST,
            currentTime - 1000 * 60 * 60 * 24, // 24小时内的数据
            currentTime
        )
        
        if (usageStatsList.isNullOrEmpty()) {
            return emptyList()
        }
        
        // 获取最近使用的应用列表
        val sortedUsageStats = usageStatsList.sortedByDescending { it.lastTimeUsed }
        val appInfoList = sortedUsageStats.mapNotNull { usageStats ->
            try {
                val packageInfo = packageManager.getPackageInfo(usageStats.packageName, 0)
                // 使用更宽松的判断条件
                val sourceDir = packageInfo.applicationInfo.sourceDir ?: ""
                
                // 默认认为是用户应用，除非明确是系统应用
                var isUserApp = true
                val systemDirs = listOf("/system/framework/", "/system/priv-app/")
                for (systemDir in systemDirs) {
                    if (sourceDir.startsWith(systemDir)) {
                        isUserApp = false
                        break
                    }
                }
                
                // 特别处理常见的用户应用
                val commonUserAppPackages = listOf(
                    "com.tencent.mm",     // 微信
                    "com.tencent.mobileqq", // QQ
                    "com.eg.android.AlipayGphone", // 支付宝
                    "com.taobao.taobao",  // 淘宝
                    "com.sina.weibo",     // 微博
                    "com.youku.phone",    // 优酷
                    "com.qiyi.video",     // 爱奇艺
                    "tv.danmaku.bili",    // 哔哩哔哩
                    "com.netease.cloudmusic", // 网易云音乐
                    "com.ss.android.ugc.aweme" // 抖音
                )
                
                val isCommonUserApp = commonUserAppPackages.any { packageInfo.packageName.startsWith(it) }
                
                if (isUserApp || isCommonUserApp) {
                    val appName = packageInfo.applicationInfo.loadLabel(packageManager).toString()
                    val appIcon = packageInfo.applicationInfo.loadIcon(packageManager)
                    AppInfo(appName, usageStats.packageName, appIcon)
                } else {
                    null
                }
            } catch (e: Exception) {
                null
            }
        }.distinctBy { it.packageName } // 去重
        
        return appInfoList.take(30)
    }
    
    /**
     * 获取所有已安装的应用（无过滤条件）
     */
    private fun getAllAppsNoFilter(): List<AppInfo> {
        return getAllAppsComprehensive()
    }
    
    /**
     * 获取所有已安装的用户应用列表（包含图标）
     */
    private fun getAllInstalledUserApps(): List<AppInfo> {
        // 检查开关状态，决定是否显示系统应用
        val showSystemApps = switchShowSystemApps.isChecked
        
        if (showSystemApps) {
            // 显示所有应用（包括系统应用）
            return getAllApps()
        } else {
            // 只显示用户应用
            return getAllUserApps()
        }
    }
    
    /**
     * 通过查询系统数据库获取所有已安装的应用
     */
    private fun getInstalledAppsFromContentResolver(): List<AppInfo> {
        // 检查开关状态，决定是否显示系统应用
        return getAllInstalledUserApps()
    }
    
    /**
     * 通过多种方式获取应用列表，确保不遗漏重要应用
     */
    private fun getAllAppsComprehensive(): List<AppInfo> {
        val appInfoList = mutableSetOf<AppInfo>() // 使用Set避免重复
        val packageManager = this.packageManager
        
        // 方法1: PackageManager获取所有应用
        try {
            val packages = packageManager.getInstalledApplications(PackageManager.GET_META_DATA)
            println("Total packages from PackageManager: ${packages.size}")
            
            for (packageInfo in packages) {
                try {
                    val appName = packageInfo.loadLabel(packageManager).toString()
                    val appIcon = packageInfo.loadIcon(packageManager)
                    val packageName = packageInfo.packageName
                    
                    appInfoList.add(AppInfo(appName, packageName, appIcon))
                    
                    // 特别关注一些关键词
                    if (packageName.contains("tencent") || appName.contains("微信") || appName.contains("WeChat")) {
                        println("Found possible WeChat related app via PackageManager: $appName ($packageName)")
                    }
                } catch (e: Exception) {
                    println("Error loading app info via PackageManager for: ${packageInfo.packageName}, error: ${e.message}")
                }
            }
        } catch (e: Exception) {
            println("Error querying installed apps via PackageManager: ${e.message}")
        }
        
        // 方法2: 通过Intent查询Launcher应用
        try {
            val intent = Intent(Intent.ACTION_MAIN, null)
            intent.addCategory(Intent.CATEGORY_LAUNCHER)
            val activities = packageManager.queryIntentActivities(intent, 0)
            println("Total launcher activities: ${activities.size}")
            
            for (activity in activities) {
                try {
                    val appName = activity.loadLabel(packageManager).toString()
                    val appIcon = activity.loadIcon(packageManager)
                    val packageName = activity.activityInfo.packageName
                    
                    // 检查是否已存在
                    if (appInfoList.none { it.packageName == packageName }) {
                        appInfoList.add(AppInfo(appName, packageName, appIcon))
                    }
                    
                    // 特别关注一些关键词
                    if (packageName.contains("tencent") || appName.contains("微信") || appName.contains("WeChat")) {
                        println("Found possible WeChat related app via Intent: $appName ($packageName)")
                    }
                } catch (e: Exception) {
                    println("Error loading app info via Intent for: ${activity.activityInfo.packageName}, error: ${e.message}")
                }
            }
        } catch (e: Exception) {
            println("Error querying launcher apps via Intent: ${e.message}")
        }
        
        // 方法3: 特别检查可能的微信相关应用
        val possibleWeChatApps = listOf(
            "com.tencent.mm",              // 微信标准包名
            "com.tencent.mobileqq",        // QQ
            "com.tencent.tim",             // TIM
            "com.wechat",                  // 可能的微信变种
            "com.tencent.wechat",          // 可能的微信变种
            "cn.com.wechat",               // 可能的微信变种
            "com.tencent.qqlite",          // QQ轻聊版
            "com.tencent.qq",              // QQ国际版等
        )
        
        for (packageName in possibleWeChatApps) {
            try {
                // 检查应用是否已安装
                val packageInfo = packageManager.getPackageInfo(packageName, 0)
                val appName = packageInfo.applicationInfo.loadLabel(packageManager).toString()
                val appIcon = packageInfo.applicationInfo.loadIcon(packageManager)
                
                if (appInfoList.none { it.packageName == packageName }) {
                    appInfoList.add(AppInfo(appName, packageName, appIcon))
                    println("Added possible WeChat related app via direct check: $appName ($packageName)")
                } else {
                    println("Possible WeChat related app already in list: $appName ($packageName)")
                }
            } catch (e: Exception) {
                // 应用未安装
                println("Possible WeChat related app not installed: $packageName")
            }
        }
        
        // 方法4: 尝试使用getResourcesForApplication检查可能的微信相关应用
        for (packageName in possibleWeChatApps) {
            try {
                val resources = packageManager.getResourcesForApplication(packageName)
                // 如果能获取到资源，说明应用存在
                println("App $packageName exists and has resources")
            } catch (e: Exception) {
                println("App $packageName does not exist or has no resources: ${e.message}")
            }
        }
        
        println("Final app list size: ${appInfoList.size}")
        return appInfoList.sortedBy { it.name }
    }
    
    /**
     * 获取所有应用（包括用户应用和系统启动器应用）
     */
    private fun getAllApps(): List<AppInfo> {
        val apps = mutableListOf<AppInfo>()
        val packageManager = this.packageManager
        // GET_META_DATA表示获取应用的元数据
        val installedApps = packageManager.getInstalledApplications(android.content.pm.PackageManager.GET_META_DATA)

        for (appInfo in installedApps) {
            // 通过appInfo.packageName可以获取应用的包名

            try {
                val appName = appInfo.loadLabel(packageManager).toString()
                val appIcon = appInfo.loadIcon(packageManager)
                val packageName = appInfo.packageName
                
                // 添加所有应用，不过滤系统应用
                apps.add(AppInfo(appName, packageName, appIcon))
            } catch (e: Exception) {
                // 忽略无法加载信息的应用
                println("Error loading all app info: ${e.message}")
            }
        }
        
        // 按应用名称排序
        return apps.sortedBy { it.name }
    }
    
    /**
     * 获取所有用户安装的应用列表
     */
    private fun getAllUserApps(): List<AppInfo> {
        val apps = mutableListOf<AppInfo>()
        val packageManager = this.packageManager
        // 获取所有已安装的应用
        val installedApps = packageManager.getInstalledApplications(PackageManager.GET_META_DATA)

        for (appInfo in installedApps) {
            try {
                // 方法1: 检查是否为系统应用（通过标志位）
                val isSystemApp = (appInfo.flags and ApplicationInfo.FLAG_SYSTEM) != 0
                
                // 方法2: 检查sourceDir路径
                val sourceDir = appInfo.sourceDir ?: ""
                val isUserApp = sourceDir.startsWith("/data/app/")
                
                // 方法3: 检查是否在系统目录中
                val isSystemDir = sourceDir.startsWith("/system/") ||
                        sourceDir.startsWith("/product/") ||
                        sourceDir.startsWith("/vendor/") ||
                        sourceDir.startsWith("/odm/") ||
                        sourceDir.startsWith("/oem/")
                
                // 如果不是系统应用，或者在用户目录下，则添加到列表
                // 特别处理微信等重要应用
                val isWeChat = appInfo.packageName.contains("tencent.mm") || 
                             appInfo.packageName.contains("wechat") ||
                             appInfo.packageName.contains("weixin")
                
                if ((!isSystemApp && !isSystemDir) || isUserApp || isWeChat) {
                    val appName = appInfo.loadLabel(packageManager).toString()
                    val appIcon = appInfo.loadIcon(packageManager)
                    val packageName = appInfo.packageName
                    // 避免重复添加
                    if (apps.none { it.packageName == packageName }) {
                        apps.add(AppInfo(appName, packageName, appIcon))
                    }
                }
            } catch (e: Exception) {
                // 忽略无法加载信息的应用
                println("Error loading app info for app: ${appInfo.packageName}, error: ${e.message}")
            }
        }
        
        // 按应用名称排序
        return apps.sortedBy { it.name }
    }
    
    /**
     * 获取桌面应用程序列表
     */
    private fun getDesktopApps(): List<AppInfo> {
        val appInfoList = mutableListOf<AppInfo>()
        val packageManager = this.packageManager

        // Android 8.0及以上版本使用LauncherApps服务
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            try {
                val launcherApps = getSystemService(LAUNCHER_APPS_SERVICE) as LauncherApps
                val profiles = launcherApps.profiles
                for (profile in profiles) {
                    val activityList = launcherApps.getActivityList(null, profile)
                    for (activity in activityList) {
                        try {
                            val appName = activity.label.toString()
                            val appIcon = activity.getIcon(0)
                            val packageName = activity.applicationInfo.packageName

                            // 避免重复添加
                            if (appInfoList.none { it.packageName == packageName }) {
                                appInfoList.add(AppInfo(appName, packageName, appIcon))
                            }
                        } catch (e: Exception) {
                            println("Error loading launcher app info: ${e.message}")
                        }
                    }
                }
            } catch (e: Exception) {
                println("Error querying launcher apps via LauncherApps: ${e.message}")
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // Android 5.0-7.1版本使用LauncherApps服务的简化版本
            try {
                val launcherApps = getSystemService(LAUNCHER_APPS_SERVICE) as LauncherApps
                val myUserHandle = android.os.Process.myUserHandle()
                val activityList = launcherApps.getActivityList(null, myUserHandle)
                for (activity in activityList) {
                    try {
                        val appName = activity.label.toString()
                        val appIcon = activity.getIcon(0)
                        val packageName = activity.applicationInfo.packageName

                        // 避免重复添加
                        if (appInfoList.none { it.packageName == packageName }) {
                            appInfoList.add(AppInfo(appName, packageName, appIcon))
                        }
                    } catch (e: Exception) {
                        println("Error loading launcher app info: ${e.message}")
                    }
                }
            } catch (e: Exception) {
                println("Error querying launcher apps via LauncherApps: ${e.message}")
            }
        }

        // 如果LauncherApps没有返回结果或版本较低，使用Intent查询
        if (appInfoList.isEmpty()) {
            try {
                val intent = Intent(Intent.ACTION_MAIN, null)
                intent.addCategory(Intent.CATEGORY_LAUNCHER)
                val activities = packageManager.queryIntentActivities(intent, 0)

                for (activity in activities) {
                    try {
                        val appName = activity.loadLabel(packageManager).toString()
                        val appIcon = activity.loadIcon(packageManager)
                        val packageName = activity.activityInfo.packageName

                        // 避免重复添加
                        if (appInfoList.none { it.packageName == packageName }) {
                            appInfoList.add(AppInfo(appName, packageName, appIcon))
                        }
                    } catch (e: Exception) {
                        println("Error loading app info for activity: ${activity.activityInfo.name}, error: ${e.message}")
                    }
                }
            } catch (e: Exception) {
                println("Error querying launcher apps: ${e.message}")
            }
        }

        // 确保重要应用（如微信）在列表中
        ensureImportantAppsIncluded(appInfoList)
        
        // 按应用名称排序
        return appInfoList.sortedBy { it.name }
    }
    
    /**
     * 确保重要应用包含在列表中
     */
    private fun ensureImportantAppsIncluded(appInfoList: MutableList<AppInfo>) {
        val importantApps = listOf(
            "com.tencent.mm",        // 微信
            "com.tencent.mobileqq",  // QQ
            "com.eg.android.AlipayGphone", // 支付宝
            "com.taobao.taobao",     // 淘宝
            "com.sina.weibo"         // 微博
        )
        
        for (packageName in importantApps) {
            // 检查是否已存在于列表中
            if (appInfoList.none { it.packageName == packageName }) {
                try {
                    val packageInfo = packageManager.getPackageInfo(packageName, 0)
                    val appName = packageInfo.applicationInfo.loadLabel(packageManager).toString()
                    val appIcon = packageInfo.applicationInfo.loadIcon(packageManager)
                    appInfoList.add(AppInfo(appName, packageName, appIcon))
                    println("Added important app: $appName ($packageName)")
                } catch (e: Exception) {
                    // 应用未安装
                    println("Important app not installed: $packageName")
                }
            }
        }
    }
    
    /**
     * 调试方法：列出所有已安装的应用
     */
    private fun debugListAllInstalledApps() {
        println("=== Debug: Listing all installed apps ===")
        val packages = packageManager.getInstalledApplications(PackageManager.GET_META_DATA)
        println("Total installed apps: ${packages.size}")
        
        var userAppCount = 0
        var systemAppCount = 0
        var weChatFound = false
        
        for (packageInfo in packages) {
            try {
                val appName = packageInfo.loadLabel(packageManager).toString()
                val packageName = packageInfo.packageName
                val sourceDir = packageInfo.sourceDir ?: "Unknown"
                
                // 判断是否为系统应用
                val isSystemApp = (packageInfo.flags and ApplicationInfo.FLAG_SYSTEM) != 0
                if (isSystemApp) {
                    systemAppCount++
                } else {
                    userAppCount++
                }
                
                // 检查是否为微信
                if (packageName == "com.tencent.mm") {
                    weChatFound = true
                    println("WECHAT FOUND: $appName ($packageName) - Source: $sourceDir - System: $isSystemApp")
                }
                
                // 打印前20个应用的信息
                if (userAppCount <= 20 && !isSystemApp) {
                    println("USER APP: $appName ($packageName) - Source: $sourceDir")
                }
                
            } catch (e: Exception) {
                println("Error loading app info for: ${packageInfo.packageName}")
            }
        }
        
        println("User apps count: $userAppCount")
        println("System apps count: $systemAppCount")
        println("WeChat found: $weChatFound")
        println("=== End debug ===")
    }

    override fun onDestroy() {
        super.onDestroy()
        floatHelper?.release()
    }
}